import os
import pcse
import matplotlib.pyplot as plt
import pandas as pd
import yaml
data_dir = r'D:\userdata\pcse_examples'

from pcse.input import PCSEFileReader
crop = PCSEFileReader(os.path.join(data_dir, "lintul3_springwheat.crop"))
soil = PCSEFileReader(os.path.join(data_dir, "lintul3_springwheat.soil"))
site = PCSEFileReader(os.path.join(data_dir, "lintul3_springwheat.site"))

#Reading model parameters
from pcse.base import ParameterProvider
parameterprovider = ParameterProvider(soildata=soil, cropdata=crop, sitedata=site)

#Reading weather data
from pcse.input import ExcelWeatherDataProvider
weatherdataprovider = ExcelWeatherDataProvider(os.path.join(data_dir, "nl1.xlsx"))
print(weatherdataprovider)

#Defining agromanagement

from pcse.input import YAMLAgroManagementReader
agromanagement = YAMLAgroManagementReader(os.path.join(data_dir, "lintul3_springwheat.amgt"))
print(agromanagement)

#Starting and running the LINTUL3 model
from pcse.models import LINTUL3
lintul3 = LINTUL3(parameterprovider, weatherdataprovider, agromanagement)
lintul3.run_till_terminate()


output = lintul3.get_output()
df = pd.DataFrame(output).set_index("day")
df.tail()

fig, axes = plt.subplots(nrows=9, ncols=2, figsize=(16,40))
for key, axis in zip(df.columns, axes.flatten()):
    df[key].plot(ax=axis, title=key)
fig.autofmt_xdate()
fig.savefig(os.path.join(data_dir, "lintul3_springwheat.png"))